<template>
  <div>
    <a-modal
      :visible="visible"
      :title="title"
      :width="1200"
      @cancel="closeModal"
      destroyOnClose
      :maskClosable="false"
      :keyboard="false"
      centered
      :bodyStyle="{
        height: 'calc(100vh - 150px)',
        overflowY: 'auto',
        boxSizing: 'border-box',
        paddingBottom: '40px',
      }"
      :footer="null"
    >
      <a-form layout="vertical">
        <div class="text-title">品牌简介</div>
        <a-row :gutter="[16, 0]">
          <a-col :span="8">
            <a-form-item label="品牌名称" v-bind="validateInfos.brand_name">
              <a-input
                v-model:value="modelRef.brand_name"
                placeholder="请输入品牌名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="业态" v-bind="validateInfos.catId">
              <a-tree-select
                v-model:value="modelRef.catId"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="请选择分类"
                tree-default-expand-all
                :tree-data="treeData"
                :fieldNames="fieldNames"
                @change="catChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="合作日期" v-bind="validateInfos.partner_date">
              <a-date-picker
                v-model:value="modelRef.partner_date"
                valueFormat="YYYY-MM-DD"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>

          <a-col :span="8">
            <a-form-item label="品牌标签">
              <a-select
                v-model:value="modelRef.brand_tag"
                :options="brandTagOptions"
                mode="multiple"
                placeholder="请选择标签"
                optionFilterProp="label"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="品牌LOGO" v-bind="validateInfos.brand_logo">
              <a-upload
                :action="$utils.imgAction"
                :headers="{ 'org-token': $store.getters.token }"
                :multiple="false"
                v-model:file-list="fileList"
                list-type="picture-card"
                @change="handleUploadChange"
                name="image"
                :data="{ dir: 'org_basic_setting' }"
                accept="image/jpg,image/jpeg,image/gif,image/png"
              >
                <div v-if="!fileList.length">
                  <plus-outlined></plus-outlined>
                  <div>上传</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="品牌简介">
              <a-textarea
                v-model:value="modelRef.brand_intro"
                placeholder="请输入品牌简介"
                :rows="3"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <div class="text-title">品牌信息</div>
        <a-row :gutter="[16, 0]">
          <a-col :span="8">
            <a-form-item
              label="品牌定位"
              v-bind="validateInfos['brand_info.position']"
            >
              <a-select
                v-model:value="modelRef.brand_info.position"
                placeholder="请选择品牌定位"
                :options="positionOptions"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="人均消费"
              v-bind="validateInfos['brand_info.consumption']"
            >
              <a-select
                v-model:value="modelRef.brand_info.consumption"
                placeholder="请选择人均消费"
                :options="pconsumptionOptions"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="经营方式"
              v-bind="validateInfos['brand_info.operation_mode']"
            >
              <a-select
                v-model:value="modelRef.brand_info.operation_mode"
                placeholder="请选择经营方式"
                :options="operationModeOptions"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="消费群体"
              v-bind="validateInfos['brand_info.consumer_group']"
            >
              <a-select
                v-model:value="modelRef.brand_info.consumer_group"
                placeholder="请选择消费群体"
                :options="consumerGroupOptions"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="注册国家">
              <a-select
                v-model:value="modelRef.brand_info.reg_country"
                placeholder="请选择注册国家"
                :options="regCountryOptions"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="现有门店">
              <a-input-number
                id="inputNumber"
                v-model:value="modelRef.brand_info.store_count"
                :min="0"
                :precision="0"
                placeholder="请输入现有门店数量"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <div class="text-title">公司信息</div>
        <a-row :gutter="[16, 0]">
          <a-col :span="8">
            <a-form-item label="所属公司">
              <a-input
                v-model:value="modelRef.company_info.company_name"
                placeholder="请输入所属公司名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="公司法人">
              <a-input
                v-model:value="modelRef.company_info.company_boss"
                placeholder="请输入公司法人姓名"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="联系电话">
              <a-input
                v-model:value="modelRef.company_info.telphone"
                placeholder="请输入联系电话"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="邮箱">
              <a-input
                v-model:value="modelRef.company_info.email"
                placeholder="请输入邮箱"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="官网地址">
              <a-input
                v-model:value="modelRef.company_info.home_url"
                placeholder="请输入官网地址"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="联系地址">
              <a-input
                v-model:value="modelRef.company_info.address"
                placeholder="请输入联系地址"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <div class="text-title">工程需求</div>
        <a-row :gutter="[16, 0]">
          <a-col :span="8">
            <a-form-item label="商铺类型">
              <a-select
                v-model:value="modelRef.engineering_requirement.store_type"
                :options="storeTypeOptions"
                mode="multiple"
                placeholder="请选择商铺类型"
                optionFilterProp="label"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="设施标签">
              <a-select
                v-model:value="modelRef.engineering_requirement.device_tag"
                :options="deviceTagOptions"
                mode="multiple"
                placeholder="请选择设施标签"
                optionFilterProp="label"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="需求面积">
              <a-select
                v-model:value="modelRef.engineering_requirement.require_area"
                :options="requireAreaOptions"
                placeholder="请选择需求面积范围"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="楼层">
              <a-row>
                <a-space>
                  <a-col>
                    <a-input
                      v-model:value="modelRef.engineering_requirement.floor"
                      placeholder="请输入楼层"
                    />
                  </a-col>
                  <a-col>-</a-col>
                  <a-col>
                    <a-select
                      v-model:value="
                        modelRef.engineering_requirement.floor_demand
                      "
                      :options="floorDemandOptions"
                      placeholder="请选择户型"
                      allowClear
                      style="width: 168px"
                    ></a-select>
                  </a-col>
                </a-space>
              </a-row>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="层高">
              <a-select
                v-model:value="modelRef.engineering_requirement.floor_height"
                :options="floorHeightOptions"
                placeholder="请选择层高"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="展示面">
              <a-select
                v-model:value="modelRef.engineering_requirement.show_area"
                :options="showAreaOptions"
                placeholder="请选择展示面宽度"
                allowClear
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="电量">
              <a-input
                v-model:value="
                  modelRef.engineering_requirement.electric_quantity
                "
                placeholder="请输入电量"
              />
            </a-form-item>
          </a-col>

          <a-col :span="8">
            <a-form-item label="排他内容">
              <a-input
                v-model:value="modelRef.engineering_requirement.exclusive_other"
                placeholder="请输入排他内容"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工程备注">
              <a-textarea
                v-model:value="
                  modelRef.engineering_requirement.engineering_info
                "
                :rows="3"
                placeholder="请输入工程备注"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="drawer-footer">
        <a-button class="mr-10" @click="closeModal">取消</a-button>
        <a-button type="primary" :loading="loadingSubmit" @click="onSubmit"
          >保存</a-button
        >
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, toRefs, computed, watch, reactive } from "vue";
import { PlusOutlined, CloseOutlined } from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import request from "@/common/utils/request";

const useForm = Form.useForm;

export default defineComponent({
  name: "AddBrand",
  components: {
    PlusOutlined,
    CloseOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    // 二级分类ID
    catId: {
      type: [String, Number],
      default: 0,
    },
    // 一级分类ID
    catFid: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    const state = reactive({
      count: 0,
      fileList: [],
      tagName: "",
      tagVisible: false,
      brandTagOptions: [],
      // 分类
      treeData: [],
      fieldNames: {
        children: "son_list",
        label: "cat_name",
        value: "id",
      },

      positionOptions: [],
      //人均消费
      pconsumptionOptions: [
        {
          label: "50以下",
          value: "50以下",
        },
        {
          label: "50-100",
          value: "50-100",
        },
        {
          label: "100-150",
          value: "100-150",
        },
        {
          label: "150-200",
          value: "150-200",
        },
        {
          label: "200-400",
          value: "200-400",
        },
        {
          label: "400以上",
          value: "400以上",
        },
      ],
      // 经营方式
      operationModeOptions: [
        {
          label: "自营",
          value: "自营",
        },
        {
          label: "加盟",
          value: "加盟",
        },
        {
          label: "直营+加盟",
          value: "直营+加盟",
        },
        {
          label: "未知",
          value: "未知",
        },
      ],
      //消费群体
      consumerGroupOptions: [
        {
          label: "小孩",
          value: "小孩",
        },
        {
          label: "青年",
          value: "青年",
        },
        {
          label: "老人",
          value: "老人",
        },
      ],
      //注册国家
      regCountryOptions: [],
      //现有门店
      storeCountOptions: [],
      // 商铺类型
      storeTypeOptions: [],
      //   设施标签
      deviceTagOptions: [],

      //   需求面积
      requireAreaOptions: [
        {
          label: "20m²以下",
          value: "20m²以下",
        },
        {
          label: "20m²-50m²",
          value: "20m²-50m²",
        },
        {
          label: "50m²-100m²",
          value: "50m²-100m²",
        },
        {
          label: "100m²-200m²",
          value: "100m²-200m²",
        },
        {
          label: "200m²-500m²",
          value: "200m²-500m²",
        },
        {
          label: "500m²-1000m²",
          value: "500m²-1000m²",
        },
        {
          label: "1000m²以上",
          value: "1000m²以上",
        },
      ],
      //  户型选择
      floorDemandOptions: [
        {
          label: "纯一楼",
          value: "纯一楼",
        },
        {
          label: "纯二楼",
          value: "纯二楼",
        },
        {
          label: "一拖二",
          value: "一拖二",
        },
        {
          label: "一拖三",
          value: "一拖三",
        },
        {
          label: "带独立通道",
          value: "带独立通道",
        },
      ],
      //   层高
      floorHeightOptions: [
        {
          label: "4米以下",
          value: "4米以下",
        },
        {
          label: "4到5米",
          value: "4到5米",
        },
        {
          label: "5到6米",
          value: "5到6米",
        },
        {
          label: "6米以上",
          value: "6米以上",
        },
      ],
      //   展示面
      showAreaOptions: [
        {
          label: "5米以下",
          value: "5米以下",
        },
        {
          label: "5到10米",
          value: "5到10米",
        },
        {
          label: "10到20米",
          value: "10到20米",
        },
        {
          label: "20到50米",
          value: "20到50米",
        },
        {
          label: "50米以上",
          value: "50米以上",
        },
      ],
      loadingSubmit: false,
    });

    const modelRef = reactive({
      catId: undefined,
      cat_id: undefined,
      cat_fid: undefined,
      brand_name: "",
      partner_date: "",
      brand_logo: "",
      brand_tag: [],
      brand_intro: "",
      // 品牌信息
      brand_info: {
        position: undefined,
        consumption: undefined,
        operation_mode: undefined,
        consumer_group: undefined,
        reg_country: undefined,
        store_count: "",
      },
      // 公司信息
      company_info: {
        company_name: "",
        company_boss: "",
        telphone: "",
        email: "",
        home_url: "",
        address: "",
      },
      // 工程需求
      engineering_requirement: {
        store_type: [],
        device_tag: [],
        require_area: undefined,
        floor: "",
        floor_demand: undefined,
        floor_height: undefined,
        show_area: undefined,
        electric_quantity: "",
        engineering_info: "",
        exclusive_other: "",
      },
    });
    const rulesRef = reactive({
      catId: [
        {
          required: true,
          message: "请选择分类",
        },
      ],
      brand_name: [
        {
          required: true,
          message: "请输入品牌名称",
        },
      ],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              modelRef.brand_logo = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        modelRef.brand_logo = "";
      }
      state.fileList = resFileList;
    };

    const closeModal = () => {
      resetFields();
      context.emit("onClose");
    };

    const onSubmit = () => {
      validate().then(() => {
        let params = {
          ...modelRef,
        };
        delete params.catId;
        state.loadingSubmit = true;
        if (props.id) {
          request
            .put("/org", `/org/brand/custom/brand/${props.id}`, params)
            .then((res) => {
              message.success("编辑成功");
              context.emit("success");
              resetFields();
              state.loadingSubmit = false;
            })
            .catch((err) => {
              state.loadingSubmit = false;
            });
          return;
        }
        request
          .post("/org", "/org/brand/custom/brand", params)
          .then((res) => {
            message.success("操作成功");
            context.emit("success");
            resetFields();
            state.loadingSubmit = false;
          })
          .catch((err) => {
            state.loadingSubmit = false;
          });
      });
    };

    const getDictList = () => {
      request
        .get("/org", "/system/dict/data", { dict_menu_alias: "orgCustomBrand" })
        .then((res) => {
          state.brandTagOptions = res.list.filter(
            (item) => item.dict_type == "org_custom_brand_tag"
          );
          state.positionOptions = res.list.filter(
            (item) => item.dict_type == "org_custom_brand_position"
          );
          state.regCountryOptions = res.list.filter(
            (item) => item.dict_type == "org_custom_brand_reg_country"
          );
          state.deviceTagOptions = res.list.filter(
            (item) => item.dict_type == "org_custom_brand_device_tag"
          );
          state.storeTypeOptions = res.list.filter(
            (item) => item.dict_type == "org_custom_brand_store_type"
          );
        });
    };

    // 获取分类
    const getCategoryQuery = () => {
      request
        .post("/org", "/org/brand/custom/brand/category/query", { filters: [] })
        .then((res) => {
          res.list.forEach((item) => {
            item.selectable = false;
          });
          state.treeData = res.list;
        });
    };

    const catChange = (value, label, { triggerNode }) => {
      modelRef.cat_id = triggerNode.props.id;
      if (triggerNode.props.parent_id) {
        modelRef.cat_fid = triggerNode.props.parent_id;
      }
    };

    const getdCustomBrand = () => {
      request.get("/org", `/org/brand/custom/brand/${props.id}`).then((res) => {
        setModelRef(res.detail);
        modelRef.catId = res.detail.cat_id || res.detail.cat_fid;
        if (res.detail.brand_logo) {
          state.fileList = [
            {
              uid: res.detail.brand_logo,
              name: res.detail.brand_logo,
              status: "done",
              url: res.detail.brand_logo,
            },
          ];
        }
      });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        if (modelRef.hasOwnProperty(key)) {
          modelRef[key] = state[key];
        }
      }
    };

    const init = () => {
      getDictList();
      getCategoryQuery();
      if (props.id) {
        getdCustomBrand();
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          state.fileList = [];
        }
      }
    );

    const title = computed(() => {
      return props.id ? "编辑品牌" : "新增品牌";
    });

    return {
      ...toRefs(state),
      title,
      closeModal,
      onSubmit,
      validateInfos,
      modelRef,
      handleUploadChange,
      catChange,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.ant-upload.ant-upload-select-picture-card) {
  width: 72px !important;
  height: 72px !important;
}
:deep(.ant-upload-list-picture-card-container) {
  width: 72px !important;
  height: 72px !important;
}
</style>
